/**
 * Copyright (C) 2011 Andrew C. Love (DNC) <dnc.app.sup@gmail.com>
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.dnc.cloak.service.gen;

import java.util.Date;
import java.util.List;

import org.apache.log4j.Logger;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.dnc.cloak.framework.context.Context;
import com.dnc.cloak.framework.persistence.CrudResult;
import com.dnc.cloak.framework.persistence.gen.ReportDefinitionCriteriaType;
import com.dnc.cloak.framework.persistence.gen.ReportDefinitionCriteriaTypeExample;
import com.dnc.cloak.framework.persistence.gen.ReportDefinitionCriteriaTypeExample.Criteria;
import com.dnc.cloak.framework.persistence.gen.ReportDefinitionCriteriaTypeMapper;
import com.dnc.cloak.framework.service.ServiceException;
/**
 * Represents services related to pallium.report_definition_criteria_type data
 *
 * This class was generated by MyBatis Generator using the cloak plug-in 
 * Generated:02-16-2011 12.14.07.009 EST
 *
 * @author <a href="mailto:drewncrew@gmail.com">Andrew C. Love</a>  
 *
 */ 	
public class ReportDefinitionCriteriaTypeServiceImpl implements ReportDefinitionCriteriaTypeService {
    private static final Logger logger = Logger.getLogger(ReportDefinitionCriteriaTypeServiceImpl.class.getName());

    private ReportDefinitionCriteriaTypeMapper mapper;

    public void setMapper(ReportDefinitionCriteriaTypeMapper mapper) {
        this.mapper = mapper;
    }
    
    public ReportDefinitionCriteriaTypeMapper getMapper( ) {
        return mapper;
    }

    /**
     * CRUD and other operations for pallium.report_definition_criteria_type
     *
     * @param context The cloak framework context 
     * @param modelList A list of model objects 
     * @param criteria Criteria for various operations
     * @return The CrudResult contains counts for update,select,insert,delete 
     * @throws ServiceException
     */
    @Transactional(propagation=Propagation.REQUIRES_NEW)
    public CrudResult<ReportDefinitionCriteriaType> crud(Context context, List<ReportDefinitionCriteriaType> modelList, ReportDefinitionCriteriaTypeExample criteria) throws ServiceException {
    
        CrudResult<ReportDefinitionCriteriaType> result = new CrudResult<ReportDefinitionCriteriaType>();

        int numInserts = 0;
        int numDeletes = 0;
        int numUpdates = 0;
        int numSelects = 0;

        //Select      
        if (modelList == null ){
			List<ReportDefinitionCriteriaType>selectList = mapper.selectByExample(criteria);		    
		    result.setResult(selectList);
            if (logger.isDebugEnabled()) {
                logger.debug("Select:" + selectList.size());
            }
            numSelects += (selectList!=null) ? selectList.size() : 0;
        }
        else{
            for (ReportDefinitionCriteriaType model : modelList) {

                if (model.isInsert() && model.isDelete()) {
                    // Do nothing
                }
                else if (model.isInsert() && model.isUpdate()) {
                	setModelLastUpdate(context, model);
                	
                    ReportDefinitionCriteriaTypeExample example = new ReportDefinitionCriteriaTypeExample();
                    Criteria modelCriteria = example.createCriteria();
                    
                    //Set the key for where clause
                    setCriteriaPrimaryKey(modelCriteria, model);

                    // First try update - Note blobs are handled by mapper.updateByExampleSelective                    
                    int updateCount = mapper.updateByExampleSelective(model, example);
                    if (updateCount > 0) {
                        numUpdates += updateCount;
                        if (logger.isDebugEnabled()) {
                            logger.debug("Update:" + numUpdates);
                        }
                    }
                    else {
                        mapper.insertSelective(model);
                        numInserts++;
                        if (logger.isDebugEnabled()) {
                            logger.debug("Insert:" + numInserts);
                        }
                    }
                }
                else if (model.isInsert()) {
                	setModelLastUpdate(context, model);
                	
                    mapper.insertSelective(model);
                    numInserts++;
                    if (logger.isDebugEnabled()) {
                        logger.debug("Insert:" + numInserts);
                    }
                }
                else if (model.isDelete()) {
                	setModelLastUpdate(context, model);
                
                    ReportDefinitionCriteriaTypeExample example = new ReportDefinitionCriteriaTypeExample();
                    Criteria modelCriteria = example.createCriteria();
                    
                    //Set the key for where clause
                    setCriteriaPrimaryKey(modelCriteria, model);

                    numDeletes += mapper.deleteByExample(example);

                    if (logger.isDebugEnabled()) {
                        logger.debug("Delete:" + numDeletes);
                    }
                }
                else if (model.isUpdate()) {
                   	setModelLastUpdate(context, model);
                
                	//Note blobs are handled by mapper.updateByExampleSelective   
                    ReportDefinitionCriteriaTypeExample example = new ReportDefinitionCriteriaTypeExample();
                    Criteria modelCriteria = example.createCriteria();

                    //Set the key for where clause
                    setCriteriaPrimaryKey(modelCriteria, model);

                    numUpdates += mapper.updateByExampleSelective(model, example);

                    if (logger.isDebugEnabled()) {
                        logger.debug("Update:" + numUpdates);
                    }
                }
                else if (model.isSelect()) {
                	List<ReportDefinitionCriteriaType> selectList = null;
                	
                	if (criteria != null) {
						selectList = mapper.selectByExample(criteria);						
                    }
                    else {
	                    ReportDefinitionCriteriaTypeExample example = new ReportDefinitionCriteriaTypeExample();
	                    Criteria modelCriteria = example.createCriteria();
                    
    	                //Set the key for where clause
        	            setCriteriaPrimaryKey(modelCriteria, model);
                    
						selectList = mapper.selectByExample(example);						
                    }
                    
                    if (result.getResult() == null){
                        result.setResult(selectList);
                    }
                    else{
                        result.getResult().addAll(selectList);
                    }

                    if (logger.isDebugEnabled()) {
                        logger.debug("Select:" + selectList.size());
                    }
                    numSelects += (selectList!=null) ? selectList.size() : 0;
                }
            }
        }

        result.setNumDelete(numDeletes);
        result.setNumInsert(numInserts);
        result.setNumUpdate(numUpdates);
        result.setNumSelect(numSelects);

        if (result.getResult()!=null)
            result.setNumSelect(result.getResult().size());

        if (logger.isDebugEnabled()){
            logger.debug(result.toString());
        }

        return result;

    }
    
	private void setCriteriaPrimaryKey(Criteria modelCriteria , ReportDefinitionCriteriaType model)	{
        modelCriteria.andCriteriaTypeEqualTo(model.getCriteriaType());
	}
	
	private void setModelLastUpdate(Context context , ReportDefinitionCriteriaType model)	{
		model.setLstUptUser(context.getSecurityContext().getPrincipal().getName());
        model.setLstUptTime(new Date());
	}
	
}
